#include "Mystdio.h"
#define FILE_MODE 0666
#define FLUSH_NOW 1
#define FLUSH_LINE 2
#define FLUSH_ALL 4

_FILE* _fopen(const char* filename,const char* flag)
{
    int openMode = 0;
    if(strcmp(flag,"r") == 0)
    {
        openMode = O_RDONLY;
    }
    else if(strcmp(flag,"w") == 0)
    {
        openMode = O_TRUNC|O_CREAT|O_WRONLY;
    }
    else if(strcmp(flag,"a") == 0)
    {
        openMode = O_APPEND|O_CREAT|O_WRONLY;
    }
    int fd = open(filename,openMode,FILE_MODE);
    _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
    fp->_fd = fd;
    fp->_bufPos = 0;
    fp->_flushMode = FLUSH_ALL;
}

size_t _fwrite(_FILE *fp,const char* s,int len)
{
    memcpy(&fp->_outBuffer[fp->_bufPos],s,len);
    fp->_bufPos += len;
    if(fp->_flushMode & FLUSH_NOW)
    {
        write(fp->_fd,fp->_outBuffer,fp->_bufPos);
    }
    else if(fp->_flushMode & FLUSH_LINE)
    {
        if(fp->_outBuffer[fp->_bufPos-1] == '\n'){ // 不考虑其他情况
            write(fp->_fd, fp->_outBuffer, fp->_bufPos);
            fp->_bufPos = 0;
        }
    }
    else if(fp->_flushMode & FLUSH_ALL)
    {
        if(fp->_bufPos == BUFSIZE){
            write(fp->_fd, fp->_outBuffer, fp->_bufPos);
            fp->_bufPos = 0;
        }
    }
}

void _fflush(_FILE *fp)
{
    if(fp->_bufPos > 0){
        write(fp->_fd, fp->_outBuffer, fp->_bufPos);
        fp->_bufPos = 0;
    }
}

void _fclose(_FILE *fp)
{
    if(fp == NULL) return;
    _fflush(fp);
    close(fp->_fd);
    free(fp);
}